package org.example;

import lombok.extern.slf4j.Slf4j;
import org.example.service.DbInfoService;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;

/**
 * 数据库信息收集主类
 */
@Slf4j
public class DbInfo {
    private static final String CONFIG_FILE = "database.properties";
    public static final String SQLITE_DB = "table_info.db";



    public static Properties loadConfig() throws IOException {
        Properties props = new Properties();
        try (InputStream input = DbInfo.class.getClassLoader().getResourceAsStream(CONFIG_FILE)) {
            if (input == null) {
                throw new IOException("找不到配置文件: " + CONFIG_FILE);
            }
            props.load(input);
        }
        return props;
    }

    public static void initSqliteDb() throws IOException {
        // 读取SQL脚本
        String sqlScript;
        try (InputStream input = DbInfo.class.getClassLoader().getResourceAsStream("db.sql")) {
            if (input == null) {
                throw new IOException("找不到SQL脚本文件: db.sql");
            }
            sqlScript = new String(input.readAllBytes());
        }
        
        // 写入SQL脚本到临时文件
        Path tempSqlFile = Files.createTempFile("init_db_", ".sql");
        Files.writeString(tempSqlFile, sqlScript);
        
        try {
            // 执行SQL脚本初始化数据库
            ProcessBuilder pb = new ProcessBuilder("sqlite3", SQLITE_DB, ".read " + tempSqlFile);
            pb.inheritIO();
            Process process = pb.start();
            int exitCode = process.waitFor();
            
            if (exitCode != 0) {
                throw new IOException("初始化SQLite数据库失败，退出码: " + exitCode);
            }
            
            log.info("SQLite数据库初始化成功");
            
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IOException("初始化SQLite数据库被中断", e);
        } finally {
            // 删除临时SQL文件
            Files.deleteIfExists(tempSqlFile);
        }
    }
}
